在Java中,可以通过多种方式来下载文件。以下是常见的几种方法介绍:
1. 使用Java标准库中的URL和URLConnection类:
```java
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class FileDownloader {
public static void downloadFile(String fileUrl
String saveTo) {
try {
URL url = new URL(fileUrl);
URLConnection connection = url.openConnection();
InputStream in = new BufferedInputStream(connection.getInputStream());
FileOutputStream out = new FileOutputStream(saveTo);
int byteRead;
while ((byteRead = in.read()) != -1) {
out.write(byteRead);
}
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String fileUrl = "http://example.com/file.txt";
String saveTo = "file.txt";
downloadFile(fileUrl
saveTo);
}
}
```
2. 使用Apache HttpComponents库:
```java
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileDownloader {
public static void downloadFile(String fileUrl
String saveTo) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(fileUrl);
try {
byte[] fileBytes = httpClient.execute(httpGet
response -> EntityUtils.toByteArray(response.getEntity()));
FileOutputStream out = new FileOutputStream(saveTo);
out.write(fileBytes);
out.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
String fileUrl = "http://example.com/file.txt";
String saveTo = "file.txt";
downloadFile(fileUrl
saveTo);
}
}
```
3. 使用Java NIO(New Input/Output):
```java
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
public class FileDownloader {
public static void downloadFile(String fileUrl
String saveTo) {
try {
URL url = new URL(fileUrl);
try (InputStream in = url.openStream();
ReadableByteChannel rbc = Channels.newChannel(in);
FileOutputStream out = new FileOutputStream(saveTo)) {
out.getChannel().transferFrom(rbc
0
Long.MAX_VALUE);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String fileUrl = "http://example.com/file.txt";
String saveTo = "file.txt";
downloadFile(fileUrl
saveTo);
}
}
```
以上是几种常见的Java下载文件的方法介绍,开发者可以根据自己的需求选择合适的方法来实现文件下载功能。
咨询微信客服
0516-6662 4183
立即获取方案或咨询top